package com.yupi.yupicturebackend.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

public class CaptchaGenerator {

    // 定义验证码字符集
    private static final String CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    // 验证码的长度
    private static final int CAPTCHA_LENGTH = 4;

    // 图像的宽度和高度
    private static final int WIDTH = 160;
    private static final int HEIGHT = 32;

    // 生成随机验证码字符串
    public static String generateCaptchaText() {
        Random random = new Random();
        StringBuilder captchaText = new StringBuilder(CAPTCHA_LENGTH);
        for (int i = 0; i < CAPTCHA_LENGTH; i++) {
            int index = random.nextInt(CHARSET.length());
            captchaText.append(CHARSET.charAt(index));
        }
        return captchaText.toString();
    }

    // 创建验证码图像
    public static BufferedImage generateCaptchaImage(String captchaText) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();

        // 设置背景颜色
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, WIDTH, HEIGHT);

        // 设置字体
        Font font = new Font("Arial", Font.BOLD, 24);
        graphics.setFont(font);

        // 设置字体颜色
        graphics.setColor(Color.BLACK);

        // 绘制验证码文本
        graphics.drawString(captchaText, 30, 24);

        // 随机添加一些干扰线
        drawRandomLines(graphics);

        // 释放资源
        graphics.dispose();

        return image;
    }

    // 随机生成干扰线
    private static void drawRandomLines(Graphics2D graphics) {
        Random random = new Random();
        graphics.setColor(Color.GRAY);
        for (int i = 0; i < 15; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            graphics.drawLine(x1, y1, x2, y2);
        }
    }

    // 将图像转换为字节数组
    public static byte[] getCaptchaImageBytes(String captchaText) throws IOException {
        BufferedImage image = generateCaptchaImage(captchaText);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        return baos.toByteArray();
    }
}

